package com.android.delivery.util;

import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 字符串操作工具包
 *
 * @author liyu
 */
public class StringUtils {

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    // 字节格式
    private static DecimalFormat df = new DecimalFormat("#.00");

    private static DecimalFormat single_df = new DecimalFormat("#.0");

    public final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    public final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    public final static ThreadLocal<SimpleDateFormat> timeFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("HH:mm");
        }
    };

    public static String getTimeIntervalDesc(long _time) {
        int s = (int) (_time / 1000);
        if (s < 30) {
            return "刚刚";
        }
        if (s < 60) {
            return s + "秒前";
        }
        if (s < 3600) {
            int m = (int) (s / 60);
            return m + "分钟前";
        }
        if (s < 86400) {
            int h = (int) (s / 3600);
            return h + "小时前";
        }
        if (s < 86400 * 30) {
            int d = (int) (s / 86400);
            return d + "天前";
        }
        if (s < 86400 * 365) {
            int m = (int) (s / (86400 * 30));
            return m + "月前";
        }
        int y = (int) (s / (86400 * 365));
        return y + "年前";
    }

//	public static long getRelativeTime() {
//
//		return System.currentTimeMillis() - AppContext.mDifferentTime;
//
//	}

    public static String getLocalTimeDesc(long time) {
        time = System.currentTimeMillis() - time;
        return getTimeIntervalDesc(time);
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param _time
     * @return boolean
     */
    public static boolean isToday(long _time) {
        boolean b = false;
        Date time = new Date(_time);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 返回long类型的今天的日期
     */
    public static long getToday() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        String curDate = dateFormater2.get().format(cal.getTime());
        curDate = curDate.replace("-", "");
        return Long.parseLong(curDate);
    }

    /**
     * 返回date类型的今天的日期
     */
    public static Date getTodayDate() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        String curDate = dateFormater2.get().format(cal.getTime());


        try {
            return dateFormater2.get().parse(curDate);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }


    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 将一个InputStream流转换成字符串
     *
     * @param is
     * @return
     */
    public static String toConvertString(InputStream is) {
        StringBuffer res = new StringBuffer();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader read = new BufferedReader(isr);
        try {
            String line;
            line = read.readLine();
            while (line != null) {
                res.append(line);
                line = read.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != isr) {
                    isr.close();
                    isr.close();
                }
                if (null != read) {
                    read.close();
                    read = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
            }
        }
        return res.toString();
    }

    public static String getDateTime(long time) {

        Date _date = new Date(time * 1000);

        return String.format("%tF", _date) + "    " + String.format("%ta", _date) + "    " + String.format("%tR", _date);
    }

    /**
     * 获取合拍名字， 最多5个字
     *
     * @param name
     * @return
     */
    public static String getNiackName(String name) {
        return getNiackName(name, 8);
    }

    public static String getNiackName(String name, int size) {
        String result = "";
        if (TextUtils.isEmpty(name)) {
            return result;
        }
        int psdLength = getStringLeng(name);
        if (psdLength > (2 * size) && size <= name.length() && size >= 0) {
            try {
                String newContent = StringUtils.subStringM(name, ((size - 1) * 2));
                result = newContent + "...";
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            result = name;
        }
        return result;
    }

    /**
     * 获取文字长度 <p>
     * 中文为2字节，英文为1字节
     *
     * @param ch
     * @return
     */
    public static int getStringLeng(CharSequence ch) {
        if (!TextUtils.isEmpty(ch)) {
            int varlength = 0;
            for (int i = 0; i < ch.length(); i++) {
                char c = ch.charAt(i);
                // changed by zyf 0825 , bug 6918，加入中文标点范围 ， TODO 标点范围有待具体化
                if (c > 0x7F) {
                    varlength += 2;
                } else {
                    varlength++;
                }
            }
            return varlength;
        }
        return 0;
    }

    /**
     * 截取字符串(含中英文)
     *
     * @param str   需要截取的字符串
     * @param count 截取字符的长度
     * @throws UnsupportedEncodingException
     */
    public static String subStringM(String str, int count) throws UnsupportedEncodingException {
        if (!TextUtils.isEmpty(str)) {
            int num = 0;// 已经截取字符的长度
            int length = 0;// 每个字符的长度
            StringBuffer sb = new StringBuffer();
            char ch[] = str.toCharArray();
            for (int i = 0; i < ch.length; i++) {
                length = String.valueOf(ch[i]).getBytes("GBK").length;
                num += length;
                if (num > count) {
                    break;
                }
                sb.append(ch[i]);
            }
            return sb.toString();
        }
        return "";
    }

    /**
     * 是否包含http
     *
     * @return
     */
    public static boolean containHttp(String str) {
        if (str.indexOf("http") != -1) {
            return true;
        }
        return false;
    }

    //获取分钟:秒钟时长
    public static String getVedioTime(long callTime) {
        int mintue = (int) (callTime / 60);
        int ss = (int) (callTime % 60);
        return String.format("%s:%s", getSS(mintue), getSS(ss));
    }

    private static String getSS(int ss) {
        if (ss < 10) {
            return "0" + ss;
        }
        return String.valueOf(ss);
    }

    /**
     * 获取星座
     *
     * @param month
     * @param day
     * @return
     */
    public static String getAstro(int month, int day) {
        String[] astro = new String[]{"摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座",
                "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"};
        int[] arr = new int[]{20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};// 两个星座分割日
        int index = month;
        // 所查询日期在分割日之前，索引-1，否则不变
        if (day < arr[month - 1]) {
            index = index - 1;
        }
        // 返回索引指向的星座string
        return astro[index];
    }

    /**
     * 获取打星星电话号码
     *
     * @param phoneNum
     * @return
     */
    public static String getFormatPhone(String phoneNum) {
        if (TextUtils.isEmpty(phoneNum)){
            return phoneNum;
        }
        StringBuilder stringBuilder = new StringBuilder();
        String start = phoneNum.substring(0, 3);
        String end = phoneNum.substring(phoneNum.length() - 4, phoneNum.length());
        stringBuilder.append(start).append("****").append(end);
        return stringBuilder.toString();
    }
}
